package main

import (
	"bytes"
	"fmt"
	"io"
	"log"
	"net/http"
	"os"
	"testing"

	"github.com/disintegration/imaging"
	ffmpeg "github.com/u2takey/ffmpeg-go"
)

func main() {
	// helloHandler := func(w http.ResponseWriter, req *http.Request) {
	// 	w.Header().Set("Content-Type", "multipart/x-mixed-replece;boundary=ffmpeg")
	// 	// io.WriteString(w, "Hello, world!\n")
	// 	ffmpeg.Input("meeting_01.mp4").
	// 		// Filter("select", ffmpeg.Args{fmt.Sprintf("gte(n,%d)", frameNum)}).
	// 		Output("pipe:", ffmpeg.KwArgs{"vframes": 300, "format": "mjpeg", "vcodec": "mjpeg"}).
	// 		// OverWriteOutput().ErrorToStdOut().
	// 		WithOutput(w).
	// 		Run()
	// 	log.Println("done")
	// }

	// http.HandleFunc("/hello", helloHandler)
	// log.Fatal(http.ListenAndServe(":8080", nil))

	// f, err := os.Open(name + "/Downloads/hello")
	// log.Println(err)
	// io.Copy(os.Stdout, f)

	// reader := ExampleReadFrameAsJpeg("meeting_01.mp4", 100)

	// io.Copy(writer, reader)
	// home, _ := os.UserHomeDir()
	// inFileName := home + "/mypipe"
	// writer, _ := os.Create("./test.jpg")
	// ffmpeg.Input(inFileName).
	// 	// Filter("select", ffmpeg.Args{fmt.Sprintf("gte(n,%d)", 200)}).
	// 	Output("pipe:", ffmpeg.KwArgs{"vframes": 1, "format": "image2", "vcodec": "mjpeg"}).
	// 	WithOutput(writer, os.Stdout).
	// 	Run()

	// ffmpeg.Input("meeting_01.mp4").
	// ffmpeg.Input(home+"/mypipe", ffmpeg.KwArgs{"vcodec": "h264", "f": "mp4"}).
	// Filter("select", ffmpeg.Args{fmt.Sprintf("gte(n,%d)", frameNum)}).
	ffmpeg.Input("/dev/video4", ffmpeg.KwArgs{
		// "pix_fmt": "yuv420p",
	}).
		Output("pipe:", ffmpeg.KwArgs{
			// Output("t.mjpeg", ffmpeg.KwArgs{
			// Output("./tt.mjpeg", ffmpeg.KwArgs{
			"vframes": 200,
			"format":  "mpjpeg",
			// "format": "image2",
			// "format": "mov",
			// "format": "mp4",
			"vcodec": "mjpeg",
			"q:v":    4, //图像质量JPEG 的正常范围是 2-31，其中 31 是最差的质量。 比例是线性的，qscale 的两倍大约是比特率的一半。 建议尝试 2-5 的值。 您可以使用值 1，但必须添加 -qmin 1 输出选项（因为默认值为 -qmin 2）。
			// "flags":  "lanczos",
			"r": 15,
			// "boundary": "--test",
			// "an": "", //不输出声音
		}).
		// OverWriteOutput().ErrorToStdOut().
		WithOutput(os.Stdout).
		Run()
}

/*
#!/bin/bash
流服务http
echo "Content-Type: multipart/x-mixed-replace;boundary=ffmpeg"
echo "Cache-Control: no-cache"
echo ""
ffmpeg -i "rtsp://192.168.60.13:554/user=admin&password=SECRET&channel=1&stream=0.sdp" -c:v mjpeg -q:v 1 -f mpjpeg -an -
*/

func myHandler(w http.ResponseWriter, r *http.Request) {

}

func TestExampleReadFrameAsJpeg(t *testing.T) {
	reader := ExampleReadFrameAsJpeg("./sample_data/in1.mp4", 5)
	img, err := imaging.Decode(reader)
	if err != nil {
		t.Fatal(err)
	}
	err = imaging.Save(img, "./sample_data/out1.jpeg")
	if err != nil {
		t.Fatal(err)
	}
}

func ExampleReadFrameAsJpeg(inFileName string, frameNum int) io.Reader {
	buf := bytes.NewBuffer(nil)
	err := ffmpeg.Input(inFileName).
		Filter("select", ffmpeg.Args{fmt.Sprintf("gte(n,%d)", frameNum)}).
		Output("pipe:", ffmpeg.KwArgs{"vframes": 1, "format": "image2", "vcodec": "mjpeg"}).
		WithOutput(buf, os.Stdout).
		Run()
	if err != nil {
		panic(err)
	}
	return buf
}

func startFFmpegProcess2(outfileName string, buf io.Reader, width, height int) <-chan error {
	log.Println("Starting ffmpeg process2")
	done := make(chan error)
	go func() {
		err := ffmpeg.Input("pipe:",
			ffmpeg.KwArgs{"format": "rawvideo",
				"pix_fmt": "rgb24", "s": fmt.Sprintf("%dx%d", width, height),
			}).
			Output(outfileName, ffmpeg.KwArgs{"pix_fmt": "yuv420p"}).
			OverWriteOutput().
			WithInput(buf).
			Run()
		log.Println("ffmpeg process2 done")
		done <- err
		close(done)
	}()
	return done
}
